<template>
  <div>
    <!-- 输入框 -->
    <el-input
      v-model="input"
      clearable
      style="width: 200px; padding-left: 5px; padding-top: 10px"
      size="medium"
      placeholder="请输入内容"
    />

    <!-- 两个按钮 -->
    <el-button v-hasBtn="'user_search'" type="primary" size="medium" style="margin-left: 10px" icon="el-icon-search" @click="search">查找</el-button>
    <el-button
      v-hasBtn="'user_add'"
      type="primary"
      size="medium"
      style="margin-left: 10px"
      icon="el-icon-edit"
      @click="addUser()"
    >添加</el-button>

    <!-- 表格 -->
    <el-table
      :data="dataBase"
      :default-sort="{prop: 'date', order: 'descending'}"
      border
      style="margin-top: 10px; margin: 10px; width: 98%;"
      :header-cell-style="{ 'text-align': 'center', 'font-size': '12px' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="用户ID" prop="uid" sortable />

      <el-table-column label="用户名称" prop="account" sortable />

      <el-table-column label="用户头像" prop="profile">
        <template slot-scope="scope">
          <el-popover>
            <div slot="reference" class="name-wrapper">
              <img :src="scope.row.profile" height="30px"></img>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="用户类型" prop="type">
        <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag v-if="scope.row.type === 'platform'" size="medium">平台管理员</el-tag>
              <el-tag v-if="scope.row.type === 'schoolAdmin'" size="medium">学校管理员</el-tag>
              <el-tag v-if="scope.row.type === 'supplier'" size="medium">供应商</el-tag>
              <el-tag v-if="scope.row.type === 'merchant'" size="medium">商户</el-tag>
            </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="270px">
        <template slot-scope="scope">
          <el-button v-hasBtn="'user_role_setting'"  type="primary" size="small" @click="setRole(scope.row)">授权角色</el-button>
          <el-button v-if="scope.row.type === 'supplier'" type="primary" size="small" @click="openSet(scope.row)">
            选择供应商</el-button>
          <el-button v-hasBtn="'user_edit'" type="primary" size="small" @click="handleClick(scope.row)">编辑</el-button>
        
          <el-button  v-if="scope.row.type !== 'schoolAdmin'" v-hasBtn="'user_delete'" type="danger" size="small" @click="open(scope.row)">
            删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      style="margin-top: 10px"
      :page-sizes="[10, 20, 50, 100]"
      :current-page.sync="pageMenu.page.page"
      :page-size="pageMenu.page.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @next-click="handleNextChange"
      @prev-click="handlePrevClick"
      @current-change="handleCurrentChange"
    />

    <el-dialog title="设置角色" :visible.sync="settingRole">
      <el-select
        v-model="seeting.roleIds"
        multiple
        filterable
        allow-create
        default-first-option
        placeholder="请选择角色"
      >
        <el-option
          v-for="item in options1"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingRole = false">取 消</el-button>
        <el-button type="primary" @click="sumitSetting()">确 定</el-button>
      </span>
    </el-dialog>



    <!-- 供应商 -->

    <el-dialog title="供应商"  :visible.sync="dialogTabled">
      <span>供应商</span>
      <el-select size="medium" style="margin-left: 20px;" v-model="formSet.supplierId" placeholder="请选择">
        <el-option
          v-for="item in optio"
          :key="item.id"
          :label="item.supplierName"
          :value="item.id">
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTabled = false">取 消</el-button>
        <el-button type="primary" @click="submitSet()">确 定</el-button>
      </span>

    </el-dialog>

    <!-- 添加用户弹窗 -->
    <el-dialog title="创建" :visible.sync="dialogTableVisible" >
      <el-form ref="form" label-position="right" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登录名" prop="account">
          <el-input v-model="form.account" clearable style="width: 350px;" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="form.pwd" clearable style="width: 350px;" />
        </el-form-item>
        <el-form-item label="所属类型" prop="type">
          <el-select v-model="form.type" clearable style="width: 350px;" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.dataValue"
              :label="item.dataName"
              :value="item.dataValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" clearable style="width: 350px;" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" style="width: 350px;" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="submitFileForm"
            :on-change="handleFileChange"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.profile" :src="form.profile" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 更新用户弹窗 -->

    <el-dialog title="编辑" :visible.sync="dialogTable" @close="resetForm()">
      <el-form ref="form" label-position="left" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登录名" prop="account">
          <el-input v-model="form.account" clearable style="width: 350px;" disabled />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="form.pwd" clearable style="width: 350px;" />
        </el-form-item>
        <el-form-item label="所属类型" prop="type">
          <el-select v-model="form.type" clearable disabled style="width: 350px;" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.dataValue"
              :label="item.dataName"
              :value="item.dataValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" clearable style="width: 350px;" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" style="width: 350px;" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="submitFileForm"
            :on-change="handleFileChange"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.profile" :src="form.profile" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTable = false">取 消</el-button>
        <el-button type="primary" @click="submitUpDate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import rsa from '@/utils/rsa'
export default {
  data() {
    return {
      dialogTabled: false,
      seeting: {
        id: 0,
        roleIds: [],
        uid: 0
      },
      formSet:{
        accountUid: '',
        supplierId: '',
      },
      settingRole: false,
      totalCount: 0,
      totalPages: '',
      input: '',
      dialogTableVisible: false,
      dialogTable: false,
      fileList: [{}],
      form: {
        id: '',
        account: '',
        pwd: '',
        type: '',
        mobile: '',
        realName: '',
        profile: ''
      },
      rules: {
        account: [
          { required: true, message: '登录名不能为空' }
        ],
        pwd: [
          { required: true, message: '密码不能为空' }
        ],
        type: [
          { required: true, message: '类型不能为空' }
        ],
        mobile: [
          { required: true, message: '电话不能为空' }
        ],
        realName: [
          { required: true, message: '真实姓名不能为空' }
        ],
        profile: [
          { required: true, message: '图片不能为空' }
        ]

      },

      optio:[],
      pageMenu: {
        page: {
          page: 1,
          pagesize: 10
        },
      relation: {
        conditions: [
        {
          colName: "type",
          ruleType: "NE",
          value: "superAdmin"
        }
        ],
      relationType: "and",
      relations: []
  }
      },
      dataBase: [{}],
      options: [{}],
      options1: [{}],
      value: '',
      value1:[],
    }
  },

  created() {
    this.getList()
    this.getAccountType()
    this.getAllRoles()
    this.getSupList()
  },

  methods: {

    openSet(val){
      this.formSet.accountUid = val.uid
      this.$request({
        url: '/customUser/getSuppliers/' + val.uid,
        method: 'get',
      }).then(res => {
          if (res.success){
              this.formSet.supplierId = res.data.id
          }
      })
      this.dialogTabled = true 
    },


    submitSet(){
        this.$request({
            url: '/customUser/setSuppliers',
            method: 'post',
            data: this.formSet
        }).then(res => {
            if (res.success){
              this.$notify.success("设置成功")
            } else {
               this.$notify.warning(res.errMessage)
            }
        })
        this.dialogTabled = false
    },


    getSupList(){
          this.$request({
              url: '/supplier/lists',
              method: 'post',
              data: {
                  page:{
                    page: 1,
                    pageSize: 1000
                  }
              }
          }).then(res => {
              if (res.success){
                  this.optio = res.data
              }
          })
      },


    sumitSetting(){
             this.$request({
                url: '/customUser/setAccountRoles',
                method: 'post',
                data: this.seeting
             }).then(res => {
                if (res.success){
                  this.$notify.success("成功")
                } else {
                  this.$notify.warning(res.errMessage)
                }
             })
        this.settingRole = false

      },

      getAllRoles(){
          this.$request({
            url: 'system/role/getAllRoles',
            method: 'get'
          }).then(res => {
              if (res.success){
                  this.options1 = res.data
              }
          })
      },

      setRole(val){
          this.seeting.id = val.id
          this.seeting.uid = val.uid
          this.$request({
              url: '/customUser/accountRoles/' + val.uid,
              method: 'get'
          }).then( res => {
              if (res.success){
                  var arr = []
                  res.data.forEach(item => {
                      arr.push(item.id)
                  })
                  this.seeting.roleIds = arr
              }
          })
          this.settingRole = true
      },


    handleCurrentChange(val) {
      this.pageMenu.page.page = val
      this.getList()
    },

    handlePrevClick(val) {
      this.pageMenu.page.page = val
      this.getList()
    },

    handleNextChange(val) {
      this.pageMenu.page.page = val
      this.getList()
    },

    handleSizeChange(val) {
      this.pageMenu.page.pagesize = val
      this.getList()
    },

    search() {
      console.log(this.input)
      if (this.input !== '') {
        this.$request({
          url: '/customUser/getAcount/' + this.input,
          method: 'get'
        }).then(res => {
          if (res.success) {
            var arr = []
            arr.push(res.data)
            this.dataBase = arr
            this.totalCount = res.totalCount
            this.totalPages = res.totalPages
          }
        })
      } else {
        this.getList()
      }
    },

    getAccountType() {
      this.$request({
        url: '/system/role/getAccountTypes',
        method: 'get'
      }).then(res => {
        if (res.success) {
          console.log(res)
          this.options = res.data
        }
      })
    },

    getList() {
      this.$request({
        url: '/customUser/accountLists',
        method: 'post',
        data: this.pageMenu
      }).then(res => {
        if (res.success) {
          this.dataBase = res.data
          this.totalCount = res.totalCount
          this.totalPages = res.totalPages
        }
      })
    },

    submit() {
      this.form.pwd = rsa.rsaPublicData(this.form.pwd)
      delete this.form.id
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$request({
            url: '/customUser/addAccount',
            method: 'post',
            data: this.form
          }).then(res => {
            if (res.success) {
             
              this.getList()
            }
          })
        }
      })
      this.dialogTableVisible = false
    },

    submitUpDate() {
      this.form.pwd = rsa.rsaPublicData(this.form.pwd)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$request({
            url: '/customUser/updateAccount',
            method: 'post',
            data: this.form
          }).then(res => {
            if (res.success) {
              this.dialogTableVisible = false
              this.getList()
            }
          })
        }
      })
    },

    submitFileForm() {
      const formData = new FormData()
      this.fileList.forEach(file => {
        formData.append('fs', file.raw)
      })
      this.$request({
        url: '/file/upload',
        method: 'post',
        data: formData
      }).then(res => {
        if (res.success) {
          this.form.profile = res.data[0].fileUrl
          this.$notify.success('上传成功')
        } else {
          this.$notify.warning(res.errMessage)
        }
      })
    },

    handleFileChange(file, fileList) {
      this.fileList = fileList
    },

    addUser() {
      this.form.profile = ''
      this.form.account = ''
      this.form.pwd = ''
      this.form.type = ''
      this.form.mobile = ''
      this.form.realName = ''
      this.dialogTableVisible = true
    },

    open(val) {
      this.$confirm('此操作将永久删除用户---' + val.account + '---,是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$request({
            url: '/customUser/deleteAccount/' + val.id,
            method: 'get'
          }).then(res => {
            if (res.success) {
              this.getList()
              this.$notify.success('删除成功')
            } else {
              this.$notify.warning(res.errMessage)
            }
          })
        })
        .catch(() => {

        })
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },

    handleClick(val) {
      this.form.id = val.id
      this.form.profile = val.profile
      this.form.account = val.account
      this.form.pwd = val.pwd
      this.form.type = val.type
      this.form.mobile = val.mobile
      this.form.realName = val.realName
      this.dialogTable = true
    },

    resetForm() {
      console.log('重置表单')
      this.$refs['form'].resetFields()
      console.log(this.form.account)
      this.form.account = ''
    }
  }
}

</script>
<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
